package com.lizk.tools.hotdeploy2.core;


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;


/**
 * 
 * <p>描述：自定义classloader</p>
 * @author lizk
 *
 */
public class ChildClassLoader extends URLClassLoader {

	String packageName = null;

	public ChildClassLoader(URL[] urls, String packageName, ClassLoader parentLoader) {
		super(urls,parentLoader);
		this.packageName = packageName;
	}

	
	/**
	 * 判断是否使用自定义加载器加载
	 * @param name
	 * @return
	 */
	public boolean isNeedLoad(String name) {
		return name.startsWith(packageName);
	}

	
	/**
	 * 重写loadClass方法，使用自己的规则加载类文件
	 */
	@Override
	public Class<?> loadClass(String name) throws ClassNotFoundException {

		Class<?> c = this.findLoadedClass(name);
		//如果需要用自定义类加载器加载，那么调用findClass方法，不走双亲委派（防止包名和jvm已经加载的类冲突）
		if (isNeedLoad(name)) {
			if (c == null) {
				c = this.findClass(name);
			}
		} else {//如果不需要，走双亲委派的原则处理（string,Object等已经被jvm加载过的类会走这里）
			c = super.loadClass(name);
		}
		return c;

	}
	
	
	public Object exeClazz(String ClazzName,String methodName,Class<?>[] parameters,Object[] objects) throws Exception{
		Object object = null;
		Class<?> clazz = this.loadClass(ClazzName);
		Object ob = clazz.newInstance();
		Method method = clazz.getMethod(methodName,parameters);
		object = method.invoke(ob,objects);
		
		return object;
	}
	
}
